import Icon from '@/component/Icon'
import { useAppSelector } from '@/store/hook'
import { TMessage } from '@/types/data'
import { Input, NavBar } from 'antd-mobile'
import { useEffect, useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import style from './index.module.scss'
import io, { Socket } from 'socket.io-client'
import { getStorage } from '@/utils/loaclStorage'
import { TOKEN_KEY } from '@/store/reducers/login'
export default function Chat () {
  // 创建socket实例
  let socket = useRef<Socket>(
    io('http://toutiao.itheima.net', {
      transports: ['websocket'],
      // 在查询字符串参数中传递 token
      query: {
        token: getStorage(TOKEN_KEY)
      }
    })
  )
  // 跳转路由
  const navigate = useNavigate()
  const profile = useAppSelector(state => state.profileer.info)

  // 消息列表
  const [messageList, setMessageList] = useState<TMessage[]>([
    { type: 'robot', msg: '亲爱的用户您好，小智同学为您服务。' },
    { type: 'user', msg: '你好' }
  ])

  // 我发送的信息
  const [msg, setMsg] = useState<string>('')

  // 连接websocket
  useEffect(() => {
    socket.current.on('connect', () => {
      console.log('connect')
    })
    socket.current.on('message', data => {
      // data为服务器返回的信息
      setMessageList(messageList => {
        return [...messageList, { type: 'robot', msg: data.msg }]
      })
    })
    return () => {
      socket.current.close()
    }
  }, [])
  // 用户聊天输入
  const userChat = (e:React.KeyboardEvent<HTMLInputElement>) =>{
    if (e.key === 'Enter' && msg !== '') {
      socket.current.emit('message', {
        msg: msg,
        timestamp: Date.now()
      })
      // 添加到列表
      setMessageList(messageList => {
        return [...messageList, { type: 'user', msg: msg }]
      })
      // 清空输入框
      setMsg('')
    }
  }
  // 聊天列表ref
  const listRef = useRef<HTMLDivElement>(null)
  useEffect(()=>{
    listRef.current!.scrollTop = listRef.current!.scrollHeight
  },[messageList])
  return (
    <div className={style.root}>
      <NavBar className='fixed-header' onBack={() => navigate('/home/profile')}>
        小智同学
      </NavBar>
      {/* 聊天列表 */}
      <div ref={listRef} className='chat-list'>
        {messageList.map((v, i) => {
          if (v.type === 'robot') {
            return (
              // 机器人
              <div key={i} className='chat-item'>
                <Icon type='iconbtn_xiaozhitongxue' />
                <div className='message'>{v.msg}</div>
              </div>
            )
          } else {
            return (
              <div key={i} className='chat-item user'>
                <img src={profile.photo} alt='' />
                <div className='message'>{v.msg}</div>
              </div>
            )
          }
        })}
      </div>
      {/* 底部消息输入框 */}
      <div className='input-footer'>
        <Input
          className='no-border input'
          placeholder='请描述您的问题'
          value={msg}
          onChange={e => setMsg(e)}
          onKeyUp={e =>userChat(e)}
        ></Input>
        <Icon type='iconbianji' />
      </div>
    </div>
  )
}
